package com.liao.badminton.redis;

import org.springframework.stereotype.Component;

import java.util.Random;

@Component
public class RedisUtil {


    static RedisOperation redisOperation;

    RedisUtil(RedisOperation redisOperation) {
        this.redisOperation = redisOperation;
    }

    /**
     * 获取过期时间
     *
     * @param prefix
     * @return
     */
    private static Long getExpire(RedisEnum prefix) {
        return prefix.getExpire();
    }

    /**
     * 保存+随机时间
     *
     * @param key
     * @param value
     * @param expire
     * @return
     */
    private static Boolean saveRoundTimes(String key, Object value, Long expire) {
        return redisOperation.set(key, value, expire + new Random().nextInt(500));
    }

    private static Boolean save(String key, Object value, Long expire) {
        return redisOperation.set(key, value, expire );
    }

    /**
     * 保存到redis
     *
     * @param prefix
     * @param key
     * @param data
     * @return
     */
    public static Boolean toSaveRedis(RedisEnum prefix, Object key, Object data) {
        return saveRoundTimes(RedisOperation.packKey(prefix, key), data, getExpire(prefix));
    }
    public static Boolean toSaveRedis(RedisEnum prefix, Object key, Object data,Long dateTime) {
        if (dateTime==null) {
            return saveRoundTimes(RedisOperation.packKey(prefix, key), data, getExpire(prefix));
        }else{
            return save(RedisOperation.packKey(prefix, key), data, dateTime);
        }
    }
    public static Boolean toSaveRedis(RedisEnum prefix, String table, String field, Object key, Object data, Long dateTime) {
        return saveRoundTimes(RedisOperation.packKey(prefix, table, field, key), data, dateTime==null?getExpire(prefix):dateTime);
    }


    public static Object toGetDate(RedisEnum prefix, Object key) {
        return redisOperation.get(RedisOperation.packKey(prefix, key));
    }
    public static Object toGetDate(RedisEnum prefix,String table,String field,  Object key) {
        return redisOperation.get(RedisOperation.packKey(prefix,  table, field, key));
    }

    public static void toFlushExpire(RedisEnum prefix,String table,String field, Object key) {
        redisOperation.expire(RedisOperation.packKey(prefix,table, field, key), getExpire(prefix));
    }
    public static void toFlushExpire(RedisEnum prefix, Object key) {
        redisOperation.expire(RedisOperation.packKey(prefix, key), getExpire(prefix));
    }
    public static void toDelete(RedisEnum prefix, Object key) {
        redisOperation.del(RedisOperation.packKey(prefix, key));
    }
    public static void toDelete(RedisEnum prefix,String table,String field, Object key) {
        redisOperation.del(RedisOperation.packKey(prefix, table, field, key));
    }

}
